<template>
	<div></div>
</template>
<script setup lang="ts" name="global-stomp-websocket">
import other from '/@/utils/other';
import { Session } from '/@/utils/storage';
import { useWebsocket } from '/@/utils/websocket';

const emit = defineEmits(['rollback']);

const props = defineProps({
	uri: {
		type: String,
	},
	protocol: {
		type: String,
		default: 'http',
	}
});

const state = reactive({
	webSocket: ref(), // webSocket实例
	lockReconnect: false, // 重连锁，避免多次重连
	maxReconnect: 6, // 最大重连次数， -1 标识无限重连
	reconnectTime: 0, // 重连尝试次数
	heartbeat: {
		interval: 30 * 1000, // 心跳间隔时间
		timeout: 10 * 1000, // 响应超时时间
		pingTimeoutObj: ref(), // 延时发送心跳的定时器
		pongTimeoutObj: ref(), // 接收心跳响应的定时器
		pingMessage: JSON.stringify({ type: 'ping' }), // 心跳请求信息
	},
});

const token = computed(() => {
	return Session.getToken();
});

const tenant = computed(() => {
	return Session.getTenant();
});

onMounted(() => {
	initWebSocket();
});

onUnmounted(() => {
	state.webSocket.close();
});

const initWebSocket = () => {
	// ws地址
	let host = window.location.hostname;
	let protocol = window.location.protocol;
	//  baseURL
	let baseURL = import.meta.env.VITE_API_URL;
	//启用netty
	let nettyEnabled = import.meta.env.VITE_WEBSOCKET_NETTY_ENABLE;
	//使用netty推送的时候才需要接口，否则不能配置
	let port = import.meta.env.VITE_WEBSOCKET_PORT;
	//  拼接ws地址
	let url = '';
	//拼接协议
	let wsUri = '';
	//启用netty服务
	if (nettyEnabled=="true") {
		protocol = props.protocol;
		url = `${host}:${port}`;
		//拼接协议
		wsUri = `${protocol}://${url}${baseURL}${other.adaptationUrl(props.uri)}?access_token=${token.value}&tenantId=${tenant.value}`;
	} else {
		//拼接协议
		wsUri = `${baseURL}${other.adaptationUrl(props.uri)}?access_token=${token.value}&tenantId=${tenant.value}`;
	}
	//创建websocket连接
	state.webSocket = useWebsocket();
	state.webSocket.init(wsUri, registerWebSocketConnection, registerWebSocketFailure);
};

const reconnect = () => {
	if (!token) {
		return;
	}
	if (state.lockReconnect || (state.maxReconnect !== -1 && state.reconnectTime > state.maxReconnect)) {
		return;
	}
	state.lockReconnect = true;
	setTimeout(() => {
		state.reconnectTime++;
		// 建立新连接
		initWebSocket();
		state.lockReconnect = false;
	}, 5000);
};

//websocket对象
let websocket = ref() as any;

const registerWebSocketConnection = () => {
	state.webSocket.subscribe('/topic/notice', topicNotice);
	state.webSocket.subscribeUser('/user/message', userMessage);
};

const topicNotice = (rsp: any) => {
	console.log(rsp);
};
const userMessage = (rsp: any) => {
	console.log(rsp);
};
const registerWebSocketFailure = () => {
	reconnect();
};
</script>
